from app import app, db
from werkzeug.security import generate_password_hash
from datetime import datetime
from sqlalchemy import text  # 添加这行导入

def create_users_direct():
    with app.app_context():
        print("开始创建测试用户...")
        
        # 检查用户是否已存在 - 使用 text() 包装 SQL
        result = db.session.execute(
            text("SELECT COUNT(*) FROM user WHERE username = 'student1'")
        ).scalar()
        
        if result > 0:
            print("用户已存在，跳过创建")
            return
        
        # 使用 SQL 直接插入用户
        current_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
        password_hash = generate_password_hash('password123')
        
        # 插入学生用户
        db.session.execute(
            text("""
                INSERT INTO user (username, email, password_hash, role, created_at, is_active) 
                VALUES (:username, :email, :password_hash, :role, :created_at, :is_active)
            """),
            {
                'username': 'student1',
                'email': 'student1@example.com',
                'password_hash': password_hash,
                'role': 'student',
                'created_at': current_time,
                'is_active': True
            }
        )
        
        # 插入教师用户
        db.session.execute(
            text("""
                INSERT INTO user (username, email, password_hash, role, created_at, is_active) 
                VALUES (:username, :email, :password_hash, :role, :created_at, :is_active)
            """),
            {
                'username': 'teacher1',
                'email': 'teacher1@example.com',
                'password_hash': password_hash,
                'role': 'teacher',
                'created_at': current_time,
                'is_active': True
            }
        )
        
        # 插入企业用户
        db.session.execute(
            text("""
                INSERT INTO user (username, email, password_hash, role, created_at, is_active) 
                VALUES (:username, :email, :password_hash, :role, :created_at, :is_active)
            """),
            {
                'username': 'company1',
                'email': 'company1@example.com',
                'password_hash': password_hash,
                'role': 'enterprise',
                'created_at': current_time,
                'is_active': True
            }
        )
        
        db.session.commit()
        print("✅ 测试用户创建成功！")
        print("📝 学生账号: student1 / password123")
        print("👨‍🏫 教师账号: teacher1 / password123")
        print("🏢 企业账号: company1 / password123")

if __name__ == '__main__':
    create_users_direct()